﻿using System;
using System.Globalization;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class AspNetCommUpload : System.Web.UI.Page
{
    //用于上传
    /// <summary>
    /// 允许上传大小(单位KB)
    /// </summary>
    int UploadImageSize;
    /// <summary>
    /// 允许上传文件类型(带[.]的扩展名)
    /// </summary>
    string UploadImageExts;
    /// <summary>
    /// 上传目录(绝对虚拟目录,以[/]开头,以[/]结尾)
    /// </summary>
    string UploadImageDir;  

    ///// <summary>
    ///// 允许上传大小(单位KB)
    ///// </summary>
    //int UploadImageSize = 300;
    ///// <summary>
    ///// 允许上传文件类型(带[.]的扩展名)
    ///// </summary>
    //string UploadImageExts = ".txt|.jpg|.exe|.doc";
    ///// <summary>
    ///// 上传目录(绝对虚拟目录,以[/]开头,以[/]结尾)
    ///// </summary>
    //string UploadImageDir = "D:/WebUpload/EditImgUpload/";  
    protected void Page_Load(object sender, EventArgs e)
    {
        string upLoadType = Request.QueryString["UpLoadType"].ToString();
        if (!IsPostBack)
        {
            switch (upLoadType)
            {
                case "mail":
                    UploadImageSize = Convert.ToInt32(ConfigurationManager.AppSettings["MailMaxFileSize"]);
                    UploadImageExts = ConfigurationManager.AppSettings["MailFileType"];
                    UploadImageDir = ConfigurationManager.AppSettings["MailUpload"];
                    doUploadPost();
                    break;
                case "file":
                    UploadImageSize = Convert.ToInt32(ConfigurationManager.AppSettings["OAUpLoadMaxFileSize"]);
                    UploadImageExts = ConfigurationManager.AppSettings["OAUpLoadFileType"];
                    UploadImageDir = ConfigurationManager.AppSettings["OAUpLoad"];
                    doUploadPost();
                    break;
                default:
                    break;
            }
            
        }
    }

    protected void doUploadPost()
    {
        HttpPostedFile PostedFile = Request.Files["Filedata"];
        if (PostedFile == null)
        {
            Response.Write("上传文件元素不存在!");
            return;
        }
        long FileLength = PostedFile.ContentLength;
        string FileName = PostedFile.FileName;
        //判断文件是否大于0字节或文件名是否为空
        if (FileLength <= 0 || string.IsNullOrEmpty(FileName))
        {
            Response.Write("未选择需要上传文件!");
            return;
        }
        if (FileName.IndexOf(".") < 0)
        {
            Response.Write("上传文件为未知文件!");
            return;
        }
        string FileExtension = FileName.Substring(FileName.LastIndexOf(".")).ToLower();

        //判断是否是允许上传的文件类型
        if (TrueFileExtension(FileExtension) == false)
        {
            Response.Write("不允许上传的文件类型,只允许上传以下类型文件:[" + UploadImageExts.Replace("|", ", ") + "]!");
            return;
        }
        long MaxFileLength = UploadImageSize * 1024;
        //判断是否在允许上传的大小之内
        if (FileLength > MaxFileLength)
        {
            Response.Write("文件大小超过最大限制(" + MaxFileLength.ToString() + "KB)!");
            return;
        }


        string NewFilePath = UploadImageDir + GetSaveFolder() + GetNewFileName(FileName);
        
        //string FileSaveDir = HttpContext.Current.Server.MapPath(NewFilePath);
        string FileSaveDir = NewFilePath;
        try
        {
            //先判断目录是否存在,不存在创建
            if (System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(FileSaveDir)) == false)
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(FileSaveDir));
            }
            PostedFile.SaveAs(FileSaveDir);
            //ReturnTrue(NewFilePath);
            Response.Write("1"+NewFilePath);
            //Response.Write("1");
        }
        catch
        {
            //如果出现错误,可能上传目录无写入权限,需检查
            //ReturnFalse("上传文件保存失败,请重试!\\n如多次重试无效,请与本网管理员联系!");
            Response.Write("0"); 
            //Response.Write("上传文件保存失败,请重试!);
                       
        }

        PostedFile = null;
        
    }
    /// <summary>
    /// 根据时间得到存放目录(以[/]结尾)
    /// </summary>
    /// <returns>yyyy-MM/</returns>
    public string GetSaveFolder()
    {
        string strdataFoider = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString();
        return "" + strdataFoider + @"/";
        
       
    }


      #region 获取指定位数的随机数
        /// <summary>
        /// 获取指定位数的随机数。
        /// </summary>
        /// <param name="RndNumCount">随机数位数。</param>
        /// <returns></returns>
        private string GetRandomStr(int RndNumCount)
        {
            string RandomStr;
            RandomStr = "";
            Random Rnd = new Random();
            for (int i = 1; i <= RndNumCount; i++)
            {
                RandomStr += Rnd.Next(0, 9).ToString();
            }
            return RandomStr;
        }
        #endregion

       

        #region 对上传的文件名进行处理  格式:年月日时分秒+两位随机数+"_"+原文件名
       /// <summary>
       /// 对上传的文件名进行处理
       /// </summary>
       /// <param name="OldFileNanme">原文件名</param>
        /// <returns>返回新文件名yyyyMMddHHmmssff12_旧文件名</returns>
        private string GetNewFileName(string OldFileNanme)
        {
            string newfile = "";
            newfile=DateTime.Now.ToString("yyyyMMddHHmmssms")+ GetRandomStr(2) +"_"+OldFileNanme;
            return newfile;
        }
        #endregion
  

    /// <summary>
    /// 判断是否是允许上传的文件类型
    /// </summary>
    /// <returns>True/False</returns>
    public bool TrueFileExtension(string FileExt)
    {
        string[] TempExtensions = UploadImageExts.ToLower().Split('|');
        for (int i = 0; i < TempExtensions.Length; i++)
        {
            if (TempExtensions[i] == FileExt) return true;
        }
        return false;
    }




}